package com.agency8x.model;

import com.agency8x.sqls.AdminSqls;
import java.util.List;

import com.agency8x.model.base.BaseAdminModel;
import com.agency8x.util.RegexUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 
 * @author SoChishun
 * @version 1.0 2017-5-22
 */
public class AdminModel extends BaseAdminModel<AdminModel> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final AdminModel me = new AdminModel().dao();

	/**
	 * 所有 sql 与业务逻辑写在 Service 中，在此放在 Model 中仅为示例
	 */
	public Page<AdminModel> paginate(int pageNumber, int pageSize, String where) {
		String sql =AdminSqls.me.getPagingSelectSql();
		String sqlFrom = AdminSqls.me.getPagingExceptSelectSql();
		if (where != null && !"".equals(where.trim())) {
			if(RegexUtil.isNumeric(where))
				sqlFrom = sqlFrom + "where user_id = " + where;
		}
		return paginate(pageNumber, pageSize, sql, sqlFrom);
	}

	public AdminModel adminEdit(String where) {
		return me.findFirst(AdminSqls.me.getFindByIdSql(), where);
	}

	public boolean updatePassword(Integer user_id, String password) {
		String sqlstmt = AdminSqls.me.getUpdatePasswordSql();
		int count = Db.update(sqlstmt, password, user_id);
		return count > 0;
	}

	public List<AdminModel> findAdmins(String user_id, String field) {
		if (StrKit.isBlank(field)) {
			field = "*";
		}
		String sqlstmt = "select " + field + " from "+AdminSqls.me.getTableName()+" where user_id in (?)";
		return find(sqlstmt, user_id);
	}

	public boolean saveRole(String user_id, String role_id) {
		String sqlstmt = AdminSqls.me.getUpdateRoleIdSql();
		int count = Db.update(sqlstmt, role_id, user_id);
		Db.update(AdminSqls.me.getUpdateRoleTitleSql());
		return count > 0;
	}

	public boolean changeStatus(Integer user_id, Integer status) {
		String sqlstmt = AdminSqls.me.getUpdateStatusSql();
		int count = Db.update(sqlstmt, status, user_id);
		return count > 0;
	}

	public String getOperatePassword(Integer userId) {
		String sqlstmt=AdminSqls.me.getFindPasswordSql();
		Record record=Db.findFirst(sqlstmt,userId);
		return record.get("operate_password","");
	}

    public List<Record> getRecords() {
        return Db.find("select * from t_user_admin");
    }

	public String getAuthRules(Integer user_id) {
		return Db.queryStr("select g.rules from t_auth_group g inner join t_user_admin u on g.id=u.role_id where u.user_id=?",user_id);
	}
}
